<template>
  <div class='box'>111
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="state.username"
          name="username"
          label="用户名"
          placeholder="用户名"
          :rules="[{ pattern, message: '请填写用户名' }]"
        />
        <van-field
          v-model="state.password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[{ pattern, message: '请填写密码' }]"
        />
        <van-field
          v-model="state.safecode"
          name="safecode"
          label="验证码"
          placeholder="验证码"
          :rules="[{ validator, message: '请填写正确验证码' }]"
        />
      </van-cell-group>
      <div class="canvans">
        <div>
          <safe-code width="100" height="40" :safecode="code" />
        </div>
      </div>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>


<script>
import { reactive, ref, onMounted } from "vue";
import safeCode from "../components/Safecode.vue";
import { getSafeCode, register } from "../api";
export default {
  setup() {
    const state = reactive({
      username: "",
      password: "",
      safecode: "",
    });

    //表单验证
    const pattern = /^\d{6,12}$/;
    const code = ref("");
    onMounted(async () => {
      let res = await getSafeCode();
      code.value = res.data.safecode;
    });
    const validator = (val) => {
      if (code.value.toLowerCase() == val.toLowerCase()) {
        return true;
      } else {
        return false;
      }
    };
    const onSubmit = async (values) => {
      delete values.safecode;
      const res = await register(values);
      if (res.errno === -1) {
        return alert(res.message);
      }
      const userId = res.data.userId;
      localStorage.setItem("userId", userId);
    };
    return {
      state,
      onSubmit,
      code,
      pattern,
      validator,
    };
  },
  components: {
    safeCode,
  },
};
</script>

<style scoped>
.canvans {
  display: flex;
  justify-content: flex-end;
  margin-right: 40px;
}
.box{
  width: 100%;
  height: 100%;
  margin-top: 55%;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.12),0 0 6px rgba(0,0,0,0.04)
}
</style>